<template>
  <div class="ResourceList">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-form
          ref="form"
          :inline="true"
          :model="formInline"
          class="demo-form-inline"
        >
          <el-form-item prop="name" label="角色名称">
            <el-input
              v-model="formInline.name"
              placeholder="角色名称"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button :disabled="isLoading" type="primary" @click="onSubmit"
              >查询</el-button
            >
            <el-button :disabled="isLoading" @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div>
        <el-button @click="openAddRole">添加角色</el-button>
      </div>
      <el-table v-loading="isLoading" :data="resources" style="width: 100%">
        <el-table-column type="index" label="编号" min-width="150">
        </el-table-column>
        <el-table-column prop="name" label="角色名称" min-width="180">
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="180">
        </el-table-column>
        <el-table-column prop="createdTime" label="添加时间" min-width="180">
        </el-table-column>
        <el-table-column label="操作" min-width="250">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="
                $router.push({
                  name: 'alloc-menu',
                  params: {
                    roleId: scope.row.id
                  }
                })
              "
              >分配菜单</el-button
            >
            <el-button
              type="text"
              @click="
                $router.push({
                  name: 'alloc-resource',
                  params: {
                    roleId: scope.row.id
                  }
                })
              "
              >分配资源</el-button
            >
            <el-button @click="handleEdit(scope.$index, scope.row)" type="text"
              >编辑</el-button
            >
            <el-button @click="deleteRoleById(scope.row.id)" type="text"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div
        style="margin-top:15px;display:flex;justify-content:center;align-items:center;"
      >
        <el-pagination
          :disabled="isLoading"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="formInline.current"
          :page-sizes="[5, 10, 20, 30]"
          :page-size="formInline.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>
    <el-dialog
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose"
    >
      <span slot="title">{{ title }}</span>
      <CreateOrEditRole ref="CreateOrEditRole" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleCancel">取 消</el-button>
        <el-button type="primary" @click="addRoleConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import { getRolePages, deleteRoleById } from '../api/index'
import CreateOrEditRole from './CreateOrEdit.vue'
import { Form } from 'element-ui'
interface Row {
  id: string;
}
export default Vue.extend({
  components: {
    CreateOrEditRole
  },
  name: 'RoleList',
  data () {
    return {
      resources: [],
      formInline: {
        name: '',
        current: 1,
        size: 5
      },
      total: 0,
      isLoading: true,
      dialogVisible: false,
      title: '添加角色'
    }
  },
  methods: {
    async deleteRoleById (id) {
      try {
        const { data } = await deleteRoleById(id)
        if (data.code === '000000') {
          this.$message.success('删除成功')
          if (this.formInline.current !== 1) {
            this.formInline.current = 1
          } else {
            this.getRolePages()
          }
        } else {
          this.$message.error('删除失败')
        }
      } catch (error) {
        console.log(error)
        this.$message.error('删除失败')
      }
    },
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          console.log(111)
          this.$refs.CreateOrEditRole.$refs.form.resetFields()
          done()
        })
        .catch(_ => {
          console.log(222)
        })
    },
    openAddRole () {
      this.title = '添加角色'
      console.log('add')
      this.dialogVisible = true
    },
    async addRoleConfirm () {
      console.log('confirm')
      try {
        await (this.$refs.CreateOrEditRole.$refs.form as Form).validate()
        await this.$refs.CreateOrEditRole.saveOrUpdateRole()
        this.$refs.CreateOrEditRole.$refs.form.resetFields()
        if (this.formInline.current !== 1) {
          this.formInline.current = 1
        } else {
          await this.getRolePages()
        }
        this.dialogVisible = false
      } catch (error) {
        console.log(error)
      }
    },
    addRoleCancel () {
      console.log('cancel')
      this.handleClose(() => {
        this.dialogVisible = false
      })
    },
    onSubmit () {
      console.log('submit!')
      if (this.formInline.current !== 1) {
        this.formInline.current = 1
      } else {
        this.getRolePages()
      }
    },
    async onReset () {
      this.$refs.form.resetFields() // 主要清除校验
      if (this.formInline.current !== 1) {
        this.formInline = {
          name: '',
          current: 1,
          size: 5
        }
      } else {
        this.formInline = {
          name: '',
          current: 1,
          size: 5
        }
        this.getRolePages()
      }
    },
    async getRolePages () {
      this.isLoading = true
      const { data } = await getRolePages(this.formInline)
      console.log(data)
      this.resources = data.data.records.map(ele => {
        ele.createdTime = this.formatDate(ele.createdTime)
        return ele
      })
      this.total = data.data.total
      this.isLoading = false
    },
    handleEdit (index: number, row: Row) {
      console.log(this.title)
      console.log(this)
      console.log(index, row)
      this.openAddRole()
      this.title = '编辑角色'
      this.$nextTick(() => {
        this.$refs.CreateOrEditRole.formInline = { ...row }
      })
    },
    async handleDelete (index: number, row: Row) {
      console.log(index, row)
    },
    handleSizeChange (val: number) {
      console.log(`每页 ${val} 条`)
      this.formInline.size = val
      if (this.formInline.current !== 1) {
        this.formInline.current = 1
      } else {
        this.getRolePages()
      }
    },
    handleCurrentChange (val: number) {
      console.log(`当前页: ${val}`)
      this.formInline.current = val
    }
  },
  watch: {
    'formInline.current': {
      immediate: true,
      handler (n: number, o: number) {
        console.log('pagechange', n, o)
        this.getRolePages()
      }
    }
  }
})
</script>

<style lang="scss" scoped></style>
